<?php
namespace App\Library\SmsGateway;

use App\Library\App;
use App\Library\Helper;
use App\Library\Http;

class Chanzornotice {

    private $gateway = 'http://sms.chanzor.com:8001/sms.aspx?action=send&account=meizanchen-yx&password=Mzcyx003&mobile=%s&content=%s&sendTime=';

    public function mt($mobile, $content) {
        $url    = sprintf($this->gateway, $mobile, rawurlencode($content));
        $http   = new Http();
        $retMsg = $http->request($url);
        if($retMsg == '') {
            $retMsg = $http->request($url);//重试一次
            if($retMsg == '') {
                return [
                    'status'      => Adapter::ERROR,
                    'status_msg'  => Adapter::ERROR_MESSAGE,
                    'gateway_msg' => '网关没有响应',
                    'send_at'     => Helper::getNow()
                ];
            }
        }
        if($retMsg != '') {
            $ret = json_decode(json_encode(simplexml_load_string($retMsg)), true);
            if(is_array($ret) && isset($ret['returnstatus'])) {
                if(strtolower($ret['returnstatus']) == 'success') {
                    return [
                        'status'      => Adapter::SUCCESS,
                        'status_msg'  => Adapter::SUCCESS_MESSAGE,
                        'gateway_msg' => isset($ret['message']) ? $ret['message'] : '',
                        'send_at'     => Helper::getNow()
                    ];
                } else {
                    App::Logger()->debug(sprintf('mobile=%s&content=%s&gateway=%s', $mobile, $content, http_build_query($ret)));
                    return [
                        'status'      => Adapter::ERROR_GATEWAY,
                        'status_msg'  => Adapter::ERROR_GATEWAY_MESSAGE,
                        'gateway_msg' => isset($ret['message']) ? $ret['message'] : '',
                        'send_at'     => Helper::getNow()
                    ];
                }
            } else {
                App::Logger()->debug(sprintf('mobile=%s&content=%s&gateway=%s', $mobile, $content, $retMsg));
                return [
                    'status'      => Adapter::ERROR_GATEWAY,
                    'status_msg'  => Adapter::ERROR_GATEWAY_MESSAGE,
                    'gateway_msg' => mb_substr($retMsg, 0, 100),
                    'send_at'     => Helper::getNow()
                ];
            }
        }
        App::Logger()->debug(sprintf('mobile=%s&content=%s&gateway=%s', $mobile, $content, http_build_query($retMsg)));
        return [
            'status'      => Adapter::ERROR_GATEWAY,
            'status_msg'  => Adapter::ERROR_GATEWAY_MESSAGE,
            'gateway_msg' => '网关返回空',
            'send_at'     => Helper::getNow()
        ];
    }
}
